package com.tina.controller;

import com.tina.entity.ChatMsg;
import com.tina.entity.Member;
import com.tina.service.ChatService;
import com.tina.service.IMemberService;
import com.tina.utils.AudioUtil;
import com.tina.utils.CommonUtil;
import com.tina.utils.Constant;
import com.tina.vo.ResponseJson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @Author tina
 * @Time 2020/12/12 下午12:09
 * @Version 1.0
 * @Content
 **/
@RestController
@Slf4j
public class HomeController {

    @Autowired
    private IMemberService memberService;

    @Value("${file.domain}")
    private String domain;

    @Value("${file.path}")
    private String path;

    @Autowired
    private ChatService chatService;

    /**
     * 如果账户存在则登录，否则直接注册
     *
     * @param member
     */
    @PostMapping("sign")
    public ResponseJson sign(Member member, HttpSession session) {
        ResponseJson responseJson = new ResponseJson();
        if (!memberService.checkeMember(member.getUserName())){
            memberService.insertMember(member);
            session.setAttribute(Constant.USER_TOKEN, member.getMemberId());
            return responseJson.success(member);
        }
        Member selectMember = memberService.selectMember(member);
        if (selectMember != null) {
            session.setAttribute(Constant.USER_TOKEN, selectMember.getMemberId());
            return responseJson.success(selectMember);
        }
        return responseJson.error("账户或者密码错误");
    }

    /**
     * 获取已登录信息
     *
     * @param session
     * @return
     */
    @GetMapping("getMember")
    public ResponseJson getMember(HttpSession session) {
        ResponseJson responseJson = new ResponseJson();
        Integer memberID = (Integer) session.getAttribute(Constant.USER_TOKEN);
        if (memberID != null) {
            return responseJson.success(memberService.selectMemberById(memberID));
        }
        return responseJson.error("请登录！");
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("uploadImg")
    public ResponseJson uploadImg(MultipartFile file, @RequestParam("sendMemberId") Integer sendMemberId, @RequestParam("acceptMemberId") Integer acceptMemberId) throws IOException {
        ResponseJson responseJson = new ResponseJson();
        if (!file.isEmpty()) {
            String prefix = "";
            String dateStr = "";
            String originalName = file.getOriginalFilename();
            prefix = originalName.substring(originalName.lastIndexOf(".") + 1);
            boolean image = CommonUtil.isImage(prefix);
            long startTime = System.currentTimeMillis();
            if (image) {
                dateStr = startTime + "." + prefix;
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path, dateStr));
                sendImgMsg(sendMemberId, acceptMemberId, domain + dateStr);
                return responseJson.success(ResponseJson.SUCCESS_MSG(), domain + dateStr);
            } else {

                return responseJson.success(ResponseJson.SUCCESS_MSG(), "不支持此格式图片！");
            }
        }
        return responseJson.error("发送失败！");
    }

    /**
     * 上传语音
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("uploadVoice")
    public ResponseJson uploadVoice(MultipartFile file, @RequestParam("sendMemberId") Integer sendMemberId, @RequestParam("acceptMemberId") Integer acceptMemberId, @RequestParam("duration") Integer duration) throws IOException, EncoderException {
        ResponseJson responseJson = new ResponseJson();
        if (!file.isEmpty()) {
            long startTime = System.currentTimeMillis();
            String voicePath = startTime + ".mp3";
            File source = new File(path, voicePath);
            file.transferTo(source);

            String s = saveVoice(voicePath, duration, sendMemberId, acceptMemberId);
            return responseJson.success(ResponseJson.SUCCESS_MSG(), s);
        }
        return responseJson.error("发送失败！");
    }

    /**
     * 保存音频并返回音频路径
     * 计算音频时长
     *
     * @param voicePath
     * @param sendMemberId
     * @param acceptMemberId
     * @return
     */
    private String saveVoice(String voicePath, Integer duration, Integer sendMemberId, Integer acceptMemberId) {
        String voice = getVoice(domain + voicePath, duration);
        sendVoice(sendMemberId, acceptMemberId, voice);
        return voice;
    }

    /**
     * 保存音频样式
     *
     * @param msg
     * @param duration
     * @return
     */
    private String getVoice(String msg, Integer duration) {
        return duration + "'" + " <i class=\"fa fa-bullhorn\" aria-hidden=\"true\"><span class='msgPlayAudio' onClick='playAudio(this)' > <audio  preload=\"auto\" class=\"audio-player\" src=\"" + msg + "\"></audio></span></i>";
    }

    /**
     * 发送语音
     *
     * @param sendMemberId
     * @param acceptMemberId
     * @param msg
     */
    private void sendVoice(Integer sendMemberId, Integer acceptMemberId, String msg) {
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setSendMemberId(sendMemberId);
        chatMsg.setAcceptMemberId(acceptMemberId);
        chatMsg.setMsg(msg);
        chatService.singleSend(chatMsg);
    }

    /**
     * 发送图片信息
     *
     * @param sendMemberId
     * @param acceptMemberId
     * @param msg
     */
    private void sendImgMsg(Integer sendMemberId, Integer acceptMemberId, String msg) {
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setSendMemberId(sendMemberId);
        chatMsg.setAcceptMemberId(acceptMemberId);
        chatMsg.setMsg("<div><a href='" + msg + "'> <img src='" + msg + "' /></a></img><div>");
        chatService.singleSend(chatMsg);
    }



}
